package com.softer.wxzj.service.impl;

import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.logic.DepReqLogic;
import com.softer.wxzj.common.util.StringUtils;
import com.softer.wxzj.entity.BaseBuildView;
import com.softer.wxzj.entity.BaseOwnerInfo;
import com.softer.wxzj.entity.FileVO;
import com.softer.wxzj.entity.SysCoreParam;
import com.softer.wxzj.mapper.BaseBuildViewMapper;
import com.softer.wxzj.mapper.SysCoreParamMapper;
import com.softer.wxzj.service.BaseBuildViewService;
import com.softer.wxzj.service.BaseOwnerInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:楼盘视图
 * @ClassName: BaseBuildViewServiceImpl
 * @author: zcz
 * @date: 2019-05-20 16:3
 */
@Service
public class BaseBuildViewServiceImpl implements BaseBuildViewService {
    @Autowired
    BaseBuildViewMapper baseBuildViewMapper;
    @Autowired
    private SysCoreParamMapper syscoreparamMapper;
    @Autowired
    private DepReqLogic depReqLogic;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private BaseOwnerInfoService baseOwnerInfoService;

    @Override
    public BaseBuildView getView(String buildNo) {
        BaseBuildView buildView = baseBuildViewMapper.getBuildAndFundById(buildNo);
        if (null == buildView) {
            return new BaseBuildView();
        }
        //未足额
        buildView.setNotDue(baseBuildViewMapper.selectNotDue(buildNo));
        //未交村
        buildView.setOverdueCount(baseBuildViewMapper.selectOverdueCount(buildNo));
        //足额
        buildView.setQuotaCount(baseBuildViewMapper.selectQuotaCount(buildNo));

        SysCoreParam emptyRoomApportionSysparam = syscoreparamMapper.getInfo("51");
        List<BaseBuildView.Build> build = baseBuildViewMapper.getBuildByBuildNo(buildNo);
        buildView.setList(build);
        for (BaseBuildView.Build b : build) {
            List<BaseBuildView.Build.Cell> cell = baseBuildViewMapper.getCellByBuildNoAndCellType(buildNo, b.getCellType());
            b.setList(cell);
            for (BaseBuildView.Build.Cell c : cell) {
                List<BaseBuildView.Build.Cell.Floor> floor = baseBuildViewMapper.getFloorByCellNo(c.getId());
                c.setList(floor);
                c.setNotDueHouses(baseBuildViewMapper.selectNotDueByCell(c.getId()));
                c.setAllHouses(baseBuildViewMapper.selectAllHouse(c.getId()));
                c.setAllStrutares(baseBuildViewMapper.selectAllStru(c.getId()));
                c.setDueHouses(baseBuildViewMapper.selectAllHouse(c.getId()) - baseBuildViewMapper.selectNotDueByCell(c.getId()));
                //给每一个单元上挂一个message的属性，展示的是未维护房间面积或房间面积为0的房间总数的提示信息
                int count = baseBuildViewMapper.countdyHouseAreaIsNullSum(c.getId(), emptyRoomApportionSysparam.getParamCode());
                if (count > 0) {
                    c.setMessage("参与分摊的房屋有" + count + "户未做房屋面积维护，请先维护房间面积。");
                }
                for (BaseBuildView.Build.Cell.Floor f : floor) {
                    List<BaseBuildView.Build.Cell.Floor.House> house = baseBuildViewMapper.getHouseByCellNoAndFloorNo(c.getId(), f.getFloorNo());
                    f.setList(house);
                    for (BaseBuildView.Build.Cell.Floor.House h : house) {
                        BaseBuildView.Build.Cell.Floor.House.HouseInfo info = baseBuildViewMapper.getHouseInfoById(h.getId());
                        info.setCellName(info.getCellName() + info.getRoomName());
                        info.setAccrAvailableBal(info.getFundBal().subtract(info.getAccountFrozen()));
                        h.setHouseInfo(info);
                    }
                    BaseBuildView.Build.Cell.Floor h = baseBuildViewMapper.selectByFloorAndCellType(buildNo, b.getCellType(), f.getFloorNo());
                    int notDueHouse = baseBuildViewMapper.selectNotDueByFloorAndCellType(buildNo, b.getCellType(), f.getFloorNo());
                    f.setDueHouses(h.getAllHouses() - notDueHouse);
                    f.setNotDueHouses(notDueHouse);
                    f.setAllStrutares(h.getAllStrutares());
                    f.setAllHouses(h.getAllHouses());
                }
            }
        }
        return buildView;
    }

    @Override
    public Map<String, Long> getHouseCountByStateOrDueState(String state, String dueState) {
        Map<String, Long> map = new HashMap<>(4);
        map.put("houseCount", Long.valueOf(NumberEnum.ZERO.getNum()));
        if (StringUtils.isNotBlank(state) || StringUtils.isNotBlank(dueState)) {
            map = baseBuildViewMapper.getHouseCountByStateOrDueState(state, dueState);
        }
        return map;
    }

    @Override
    public Map<String, Object> getViewHead(String regionNo) {
        Map<String, Object> map = new HashMap<>(6);
        Map<String, String> rMap = baseBuildViewMapper.getRegionNameAndRegionNoByRegionNo(regionNo);
        if (null != rMap) {
            map.put("regionNo", rMap.get("regionNo"));
            map.put("regionName", rMap.get("regionName"));
        }
        List<Map<String, String>> buildList = baseBuildViewMapper.getBuildNameListByRegionNo(regionNo);
        //有分区拼接分区
        buildList.forEach(b -> {
            if (!StringUtils.isEmpty(b.get("subRegionName"))) {
                b.put("buildName", b.get("buildName") + "(" + b.get("subRegionName") + ")");
            }
        });

        map.put("buildList", buildList);
        return map;
    }

    @Override
    public Map<String, Object> getHouseCount(String buildNo) {
        Map<String, Object> map = initHouseCountMap();
        List<Map<String, Object>> stateCountList = baseBuildViewMapper.getHouseCountGroupByState(buildNo);
        List<Map<String, Object>> dueStateCountList = baseBuildViewMapper.getHouseCountGroupByDueState(buildNo);
        List<Map<String, Object>> dueApplyStateList = baseBuildViewMapper.getHouseCountGroupByDueApplyState(buildNo);
        return setHouseCountMap(stateCountList, dueStateCountList, dueApplyStateList, map);
    }

    @Override
    public Map<String, Object> getHouseInfoDetail(String id, String arcType) {
        Map<String, Object> houseMap = baseBuildViewMapper.getHouseInfoDetailByHouseId(id);
        List<Map<String, Object>> ownerList = baseBuildViewMapper.getOwnerInfoByHouseId(id);
        List<Map<String, Object>> list = getOwnerMap(ownerList, arcType, id);
        return getHouseInfoDetailMap(id, houseMap, list);
    }

    /**
     * 创建业主map
     *
     * @return
     */
    private List<Map<String, Object>> getOwnerMap(List<Map<String, Object>> ownerList, String arcType, String houseId) {
        for (Map<String, Object> m : ownerList) {
            String infoType = String.valueOf(m.get("infoType"));
            if (NumStrEnum.ZERO.getNum().equals(infoType)) {
                String id = (String) m.get("id");
                // 查询图档信息
                List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
                m.put("fileTypeList", fileVOList);
                //查询附房信息集合
                List<BaseOwnerInfo> subHouseList = baseOwnerInfoService.getSubHouseList(houseId);
                m.put("baseOwnerInfoList", subHouseList);
            }
            String time = String.valueOf(m.get("contractDate"));
            String purTime = String.valueOf(m.get("purchaseDate"));
            if (!"null".equals(purTime)) {
                m.put("purchaseDate", purTime);
            } else {
                m.put("purchaseDate", null);
            }
            if (!"null".equals(time)) {
                m.put("contractDate", time);
            } else {
                m.put("contractDate", null);
            }
        }
        return ownerList;
    }

    /**
     * 创建房屋详情
     *
     * @return
     */
    private Map<String, Object> getHouseInfoDetailMap(String id, Map<String, Object> houseMap, List<Map<String, Object>> list) {
        Map<String, Object> map = new HashMap<>(20);
        if (null == houseMap) {
            houseMap = new HashMap<>(8);
        }
        BigDecimal fundBal = new BigDecimal(houseMap.get("fundBal").toString());
        BigDecimal accountFrozen = new BigDecimal(houseMap.get("accountFrozen").toString());
        BigDecimal nowBal = fundBal.subtract(accountFrozen);
        //看是否缴存记账
        if (NumStrEnum.ONE.getNum().equals(houseMap.get("state").toString()) && !NumStrEnum.FOUR.getNum().equals(houseMap.get("dueState").toString())) {
            map.put("keepState", houseMap.get(NumStrEnum.ONE.getNum()));
        } else {
            map.put("keepState", houseMap.get(NumStrEnum.ZERO.getNum()));
        }
        map.put("fundBal", houseMap.get("fundBal"));
        map.put("accountFrozen", houseMap.get("accountFrozen"));
        map.put("houseUseName", houseMap.get("houseUseName"));
        map.put("houseAttrName", houseMap.get("houseAttrName"));
        map.put("annexeArea", houseMap.get("annexeArea"));
        map.put("housingArea", houseMap.get("housingArea"));
        map.put("cellNo", houseMap.get("cellNo"));
        map.put("firstModeName", houseMap.get("firstModeName"));
        //当前可使用金额
        map.put("nowBal", nowBal);
        map.put("id", id);
        map.put("state", houseMap.get("state"));
        map.put("flowInProgress", houseMap.get("flowInProgress"));
        map.put("buildNo", houseMap.get("buildNo"));
        map.put("depType", houseMap.get("depType"));
        map.put("buildId", houseMap.get("buildId"));
        map.put("floorNo", houseMap.get("floorNo"));
        map.put("roomNo", houseMap.get("roomNo"));
        map.put("roomName", houseMap.get("roomName"));
        map.put("houseAttr", houseMap.get("houseAttr"));
        map.put("houseUse", houseMap.get("houseUse"));
        map.put("ownerState", houseMap.get("ownerState"));
        map.put("struArea", houseMap.get("struArea"));
        map.put("houseSite", houseMap.get("houseSite"));
        map.put("firstMode", houseMap.get("firstMode"));
        map.put("dueState", houseMap.get("dueState"));
        map.put("dueApplyState", houseMap.get("dueApplyState"));
        map.put("houseName", houseMap.get("houseName"));
        map.put("zoneName", houseMap.get("zoneName"));
        map.put("accountFrozenAll", houseMap.get("accountFrozenAll"));
        map.put("accrBal", houseMap.get("accrBal"));
        map.put("bankCode", houseMap.get("bankCode"));
        map.put("bankCodeName", houseMap.get("bankCodeName"));
        map.put("availableBal", houseMap.get("availableBal"));
        int count = baseBuildViewMapper.getJCCountByHouseId(id);
        //是否有有效的缴存记录  1是 0否
        map.put("isDisplayBal", count > 0 ? NumStrEnum.ONE.getNum() : NumStrEnum.ZERO.getNum());
        //获取房屋是否已缴存或者缴存中   1是  0否
        String dueState = depReqLogic.getIsDueState(id);
        if (NumStrEnum.THREE.getNum().equals(houseMap.get("state").toString()) || NumStrEnum.FOUR.getNum().equals(houseMap.get("state").toString())) {
            dueState = NumStrEnum.ONE.getNum();
        }
        map.put("isDueState", dueState);
        map.put("ownerList", list);
        return map;
    }


    /**
     * 初始化条数map
     *
     * @return
     */
    private Map<String, Object> initHouseCountMap() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("vacantCount", 0);
        map.put("inCancelCount", 0);
        map.put("inQuitCount", 0);
        map.put("quotaCount", 0);
        map.put("moreCount", 0);
        map.put("lessCount", 0);
        map.put("overdueCount", 0);
        map.put("applicationCount", 0);
        map.put("inAuditCount", 0);
        map.put("notDue", 0);
        return map;
    }

    /**
     * 赋值给条数map
     *
     * @return
     */
    private Map<String, Object> setHouseCountMap(List<Map<String, Object>> stateCountList,
                                                 List<Map<String, Object>> dueStateCountList,
                                                 List<Map<String, Object>> dueApplyStateList,
                                                 Map<String, Object> map) {
        for (Map<String, Object> stateCount : stateCountList) {
            String state = String.valueOf(stateCount.get("state"));
            //状态 0 空房 1 已售 2销户 3待销户
            switch (state) {
                case "0":
                    map.put("vacantCount", stateCount.get("count"));
                    break;
                case "3":
                    map.put("inCancelCount", stateCount.get("count"));
                    break;
                case "4":
                    map.put("inQuitCount", stateCount.get("count"));
                    break;
            }
        }
        for (Map<String, Object> dueStateCount : dueStateCountList) {
            String dueState = String.valueOf(dueStateCount.get("dueState"));
            //缴存状态 1足额 2多缴 3少缴 4未交 5免交
            switch (dueState) {
                case "1":
                    map.put("quotaCount", dueStateCount.get("count"));
                    break;
                case "2":
                    map.put("moreCount", dueStateCount.get("count"));
                    break;
                case "3":
                    map.put("lessCount", dueStateCount.get("count"));
                    break;
                case "4":
                    map.put("overdueCount", dueStateCount.get("count"));
                    break;
            }
        }
        for (Map<String, Object> dueApplyStateCount : dueApplyStateList) {
            String dueApplyState = String.valueOf(dueApplyStateCount.get("dueApplyState"));
            //0待申请 1审核中  2审核通过 （缴存中）3审核失败，4正常（缴存结束）
            switch (dueApplyState) {
                //case NumStrEnum.ZERO.getNum() : map.put("applicationCount",dueApplyStateCount.get("count")); break;
                case "0":
                    map.put("noAuditCount", dueApplyStateCount.get("count"));
                    break;
                case "1":
                    map.put("inAuditCount", dueApplyStateCount.get("count"));
                    break;
                case "2":
                    map.put("passAuditCount", dueApplyStateCount.get("count"));
                    break;
            }
        }
        return map;
    }

}
